package com.webSocket.test.WebSocket;

import com.google.gson.Gson;
import com.webSocket.test.entity.MySocketMessage;
import com.webSocket.test.entity.User;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class SocketHandler extends TextWebSocketHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(SocketHandler.class);

    //已建立连接的用户

    private static final Map<String,WebSocketSession> users = new ConcurrentHashMap<>();
    private static final Map<String, User> userMap = new ConcurrentHashMap<>();

    /**
     * 处理前端发送的文本信息
     * js调用websocket.send时候，会调用该方法
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String username = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        JSONObject jsonObject = JSONObject.fromObject(message.getPayload());
        MySocketMessage mySocketMessage = (MySocketMessage) JSONObject.toBean(jsonObject, MySocketMessage.class);
        // 获取提交过来的消息详情
        LOGGER.debug("收到用户 " + username + "的消息:" + message.toString());
        //回复一条信息，


        mySocketMessage.setUserList(userMap.values().stream().collect(Collectors.toList()));
        if("group".equals(mySocketMessage.getMessageType())){
            mySocketMessage.setMessage(username+":"+mySocketMessage.getMessage());
            String text = new Gson().toJson(mySocketMessage);
            sendMessageToUsers(new TextMessage(text));
        }else {
            mySocketMessage.setMessage(username+"对"+userMap.get(mySocketMessage.getToUser()).getName()+"说:"+mySocketMessage.getMessage());
            String text = new Gson().toJson(mySocketMessage);
            sendMessageToUser(session.getId(),new TextMessage(text));
            sendMessageToUser(mySocketMessage.getToUser(),new TextMessage(text));
        }
    }


    /**
     * 当新连接建立的时候，被调用
     * 连接成功时候，会触发页面上onOpen方法
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {

        String username = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        users.put(session.getId(),session);
        User user = new User(session.getId());
        user.setName(username);
        userMap.put(session.getId(),user);
        LOGGER.info("用户 " + username + " Connection Established");
        MySocketMessage mySocketMessage = new MySocketMessage(username + " connect");
        mySocketMessage.setUserList(userMap.values().stream().collect(Collectors.toList()));
        String text = new Gson().toJson(mySocketMessage);
        sendMessageToUsers(new TextMessage(text));
//        session.sendMessage(new TextMessage("hello wellcome"+username));
    }

    /**
     * 当连接关闭时被调用
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status){
        String username = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        LOGGER.info("用户 " + username + " Connection closed. Status: " + status);
        users.remove(session.getId());
        userMap.remove(session.getId());
    }

    /**
     * 传输错误时调用
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String username = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        if (session.isOpen()) {
            session.close();
        }
        LOGGER.debug("用户: " + username + " websocket connection closed......");
        users.remove(session.getId());
        userMap.remove(session.getId());
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users.values()) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个用户发送消息
     *
     * @param
     * @param message
     */
    public void sendMessageToUser(String userId, TextMessage message) {
        for (String sessionId : users.keySet()) {
            if (sessionId.equals(userId)) {
                try {
                    if (users.get(userId).isOpen()) {
                        users.get(userId).sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }



}
